package cn.edu.xmu.restfuldemo.service;

import cn.edu.xmu.restfuldemo.dao.OrdersDao;
import cn.edu.xmu.restfuldemo.model.Orders;
import cn.edu.xmu.restfuldemo.model.OrdersPo;
import cn.edu.xmu.restfuldemo.model.OrderRetVo;
import cn.edu.xmu.restfuldemo.model.OrdersVo;
import cn.edu.xmu.restfuldemo.model.VoObject;
import cn.edu.xmu.restfuldemo.service.OrderService;
import cn.edu.xmu.restfuldemo.util.ResponseCode;
import cn.edu.xmu.restfuldemo.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class  OrderService  {

    @Autowired
    OrdersDao orderDao;


    public ReturnObject<VoObject> findById(Integer id) {
        OrdersPo orderPo=new OrdersPo();
        orderPo.setId(id);
        ReturnObject<VoObject> returnOrder;
        ReturnObject<List<Orders>> returnObject = orderDao.fineorder(orderPo);
        if (returnObject.getCode().equals(ResponseCode.OK)) {
            if (returnObject.getData().size() == 1) {
                returnOrder = new ReturnObject<>(returnObject.getData().get(0));
            } else{
                returnOrder = new ReturnObject<>(ResponseCode.RESOURCE_ID_NOTEXIST);
            }
        }else{
            returnOrder = new ReturnObject<>(returnObject.getCode(), returnObject.getErrmsg());
        }
        return returnOrder;
    }


    @Transactional
    public ReturnObject<VoObject> create(OrdersVo orderVo) {
        Orders order = orderVo.createOrder();
        ReturnObject<Orders> retObj = orderDao.createOrder(order);
        ReturnObject<VoObject> retOrder;
        if (retObj.getCode().equals(ResponseCode.OK)) {
            retOrder = new ReturnObject<>(retObj.getData());
        }else{
            retOrder = new ReturnObject<>(retObj.getCode(), retObj.getErrmsg());
        }
        return retOrder;
    }
}
